package com.huawei.hwclouds.lubanops.demo.shoppingcart.client;

import com.huawei.hwclouds.lubanops.demo.common.client.HttpCallResult;
import com.huawei.hwclouds.lubanops.demo.common.client.HttpClient;
import com.huawei.hwclouds.lubanops.demo.common.client.LubanopsClientBase;
import com.huawei.hwclouds.lubanops.demo.common.exception.ErrorCodeException;
import com.huawei.hwclouds.lubanops.demo.common.model.HttpHeaderMap;
import com.huawei.hwclouds.lubanops.demo.common.util.ConfigServiceUtil;

/**
 * APM MASTER 相关的服务
 */
public class ShoppingCartServiceClient extends LubanopsClientBase {

    private static final String CONFIG_SERVER_ADDRESS = ConfigServiceUtil.getConfigServerAddress(
        "shopping-cart-service-client.properties", ShoppingCartHeaderFactory.class);

    private static final HttpClient CLIENT = ConfigServiceUtil.getHttpClient(
        "shopping-cart-service-client.properties", ShoppingCartHeaderFactory.class);

    private static final String API_ADDRESS_PREFIX = "/apm2/demo/shopping/cart/";

    private ShoppingCartServiceClient() {
    }

    /**
     * 此方法用于初始化这个类，读取配置文件，判断合法性 <br>
     *
     * @author y00438022
     * @since 2020年3月24日
     */
    public static void init() {

    }

    /**
     * 添加商品
     *
     * @param model
     */
    public static void addShoppingCart(String model) {
        String url = CONFIG_SERVER_ADDRESS + API_ADDRESS_PREFIX + "/append";
        CLIENT.sendPostJSON(url, HttpHeaderMap.getDefaultHeader(), model);
    }

    /**
     * 结算
     *
     * @param models 参数
     */
    public static void settleAccounts(String models) {
        String url = CONFIG_SERVER_ADDRESS + API_ADDRESS_PREFIX + "settle/accounts";
        CLIENT.sendPostJSON(url, HttpHeaderMap.getDefaultHeader(), models);
    }

    public static HttpCallResult queryShoppingCarts(String param) {
        String url = CONFIG_SERVER_ADDRESS + API_ADDRESS_PREFIX + "shoppingCarts";
        return CLIENT.sendPostJSON(url, HttpHeaderMap.getDefaultHeader(), param);
    }

    public static void clear() {
        String url = CONFIG_SERVER_ADDRESS + API_ADDRESS_PREFIX + "clear";
        CLIENT.sendGet(url, null, HttpHeaderMap.getDefaultHeader());
    }

    public static String error(int id) {
        String url = CONFIG_SERVER_ADDRESS + API_ADDRESS_PREFIX + "error/";
        HttpCallResult result = CLIENT.sendGet(url + id, HttpHeaderMap.getDefaultHeader());
        if (result.getStatus() != 200) {
            throw new ErrorCodeException("shoppingCart service has error", "500", "请求" + url + "error",
                result.getContent());
        }
        return result.getContent();
    }
}
